package com.example.paper1024.imply;

import com.example.paper1024.dao.PaperDao;
import com.example.paper1024.entity.Paper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Service;

import java.sql.PreparedStatement;
import java.util.List;

@Service
public class PaperService implements PaperDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    // 获取所有论文，按id降序排序
    @Override
    public List<Paper> getAllPapers() {
        String sql = "SELECT * FROM soft_journal ORDER BY id DESC";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Paper.class));
    }

    @Override
    public Paper getPaperById(int id) {
        String sql = "SELECT * FROM soft_journal WHERE id = ?";
        return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(Paper.class), id);
    }

    @Override
    public Integer insertPaper(Paper paper) {
        String sql = "INSERT INTO soft_journal (title, author, abstract1, pubdate) VALUES (?, ?, ?, ?)";
        return jdbcTemplate.update(sql, paper.getTitle(), paper.getAuthor(), paper.getAbstract1(), paper.getPubdate());
    }

    // 新增论文并返回新增的Paper对象
    public Paper addPaperAndReturn(Paper paper) {
        String sql = "INSERT INTO soft_journal (title, author, abstract1, pubdate) VALUES (?, ?, ?, ?)";
        KeyHolder keyHolder = new GeneratedKeyHolder();
        jdbcTemplate.update(connection -> {
            PreparedStatement ps = connection.prepareStatement(sql, new String[] { "id" });
            ps.setString(1, paper.getTitle());
            ps.setString(2, paper.getAuthor());
            ps.setString(3, paper.getAbstract1());
            ps.setDate(4, java.sql.Date.valueOf(paper.getPubdate()));
            return ps;
        }, keyHolder);
        Number key = keyHolder.getKey();
        if (key != null) {
            paper.setId(key.intValue());
        }
        return paper;
    }

    @Override
    public Integer updatePaper(Paper paper) {
        String sql = "UPDATE soft_journal SET title = ?, author = ?, abstract1 = ?, pubdate = ? WHERE id = ?";
        return jdbcTemplate.update(sql, paper.getTitle(), paper.getAuthor(), paper.getAbstract1(), paper.getPubdate(), paper.getId());
    }

    @Override
    public Integer deletePaper(int id) {
        String sql = "DELETE FROM soft_journal WHERE id = ?";
        return jdbcTemplate.update(sql, id);
    }
}
